package com.ruoyi.web.controller.check.patient;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.LabinfoItemData;
import com.ruoyi.system.domain.LabinfoSampleData;
import com.ruoyi.system.domain.Patient;
import com.ruoyi.system.service.ILabinfoItemDataService;
import com.ruoyi.system.service.ILabinfoSampleDataService;
import com.ruoyi.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/check/item")
public class LabinfoItemDataController extends BaseController {
    @Autowired
    private ILabinfoItemDataService labinfoItemDataService;

    @Autowired
    private ILabinfoSampleDataService iLabinfoSampleDataService;

    @Autowired
    private ISysDictDataService sysDictDataService;


    /**
     * 查询【项目】列表
     */
    @PreAuthorize("@ss.hasPermi('check:item:list')")
    @GetMapping("/list")
    public TableDataInfo list(LabinfoItemData labinfoItemData)
    {
        startPage();
        List<LabinfoItemData> list = labinfoItemDataService.selectLabinfoItemDataList(labinfoItemData);
        return getDataTable(list);
    }

    /**
     * 导出【项目】列表
     */
    @PreAuthorize("@ss.hasPermi('check:item:export')")
    @Log(title = "【项目】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LabinfoItemData labinfoItemData)
    {
        List<LabinfoItemData> list = labinfoItemDataService.selectLabinfoItemDataList(labinfoItemData);
        ExcelUtil<LabinfoItemData> util = new ExcelUtil<LabinfoItemData>(LabinfoItemData.class);
        util.exportExcel(response, list, "【项目】数据");
    }

    /**
     * 获取【项目】详细信息
     */
    @PreAuthorize("@ss.hasPermi('check:item:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(labinfoItemDataService.selectLabinfoItemDataById(id));
    }

    /**
     * 新增【项目】
     */
    @PreAuthorize("@ss.hasPermi('check:item:add')")
    @Log(title = "【项目】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LabinfoItemData labinfoItemData)
    {
        return toAjax(labinfoItemDataService.insertLabinfoItemData(labinfoItemData));
    }

    /**
     * 修改【项目】
     */
    @PreAuthorize("@ss.hasPermi('check:item:edit')")
    @Log(title = "【项目】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LabinfoItemData labinfoItemData)
    {
        return toAjax(labinfoItemDataService.updateLabinfoItemData(labinfoItemData));
    }

    /**
     * 删除【项目】
     */
    @PreAuthorize("@ss.hasPermi('check:item:remove')")
    @Log(title = "【项目】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(labinfoItemDataService.deleteLabinfoItemDataByIds(ids));
    }



    //样本入库 按照类型获取样本数据
    @PreAuthorize("@ss.hasPermi('check:item:list1')")
    @GetMapping(value = "/getItemListBySampleDecWay1")
    public TableDataInfo getItemListBySampleDecWay1(LabinfoItemData labinfoItemData) {
        startPage();
        LoginUser loginUser = SecurityUtils.getLoginUser();//获取当前登录信息
        SysUser sysUser = loginUser.getUser();
        List<Map> list = new ArrayList<>();
        if(sysUser != null){
            String isRegister = sysUser.getIsRegister() == null? "0":sysUser.getIsRegister() ;//是否注册 1已注册，0未注册
            if(StringUtils.isNotEmpty(isRegister) && isRegister.equals("1")){//注册，则代表客户
                list = labinfoItemDataService.getItemListBySampleDecWay1(labinfoItemData,sysUser);
            }else{
                list = labinfoItemDataService.getLabinfoItemDataList(labinfoItemData);
            }
            if(CollectionUtil.isNotEmpty(list)){
                List<String> sampleSerialNumberList = list.stream().map(item -> item.get("sample_serial_number").toString()).collect(Collectors.toList());
                List<LabinfoSampleData> sampleList = iLabinfoSampleDataService.getSampleListByList(sampleSerialNumberList);
                if(CollectionUtil.isNotEmpty(sampleList)){ //sampleList转成map
                    Map<String, List<LabinfoSampleData>> map = sampleList.stream()
                            .collect(Collectors.groupingBy(LabinfoSampleData::getSampleSerialNumber));
                    //遍历list
                    list.stream().forEach(map1 -> {
                        if(map1.get("sample_serial_number") != null){
                            String sampleSerialNumber = map1.get("sample_serial_number").toString();
                            if(StringUtils.isNotEmpty(sampleSerialNumber) && map.get(sampleSerialNumber) != null){
                                List<LabinfoSampleData> labinfoSampleDataList = map.get(sampleSerialNumber);
                                if(CollectionUtil.isNotEmpty(labinfoSampleDataList)){
                                    map1.put("sampleList",labinfoSampleDataList);
                                }
                            }
                        }
                    });
                }
            }
        }
        return getDataTable(list);
    }


    //检测进度 按照类型获取样本数据
    @PreAuthorize("@ss.hasPermi('check:item:list2')")
    @GetMapping(value = "/getItemListBySampleDecWay2")
    public TableDataInfo getItemListBySampleDecWay2(LabinfoItemData labinfoItemData) {
        startPage();
        LoginUser loginUser = SecurityUtils.getLoginUser();//获取当前登录信息
        SysUser sysUser = loginUser.getUser();
        List<LabinfoItemData> list = new ArrayList<>();
        if(sysUser != null){
            String isRegister = sysUser.getIsRegister() == null? "0":sysUser.getIsRegister() ;//是否注册 1已注册，0未注册
            if(StringUtils.isNotEmpty(isRegister) && isRegister.equals("1")){//注册，则代表客户
                list = labinfoItemDataService.getItemListBySampleDecWay2(labinfoItemData,sysUser);
            }else{
                list = labinfoItemDataService.selectLabinfoItemDataList(labinfoItemData);
            }
            if(CollectionUtil.isNotEmpty(list)){
                List<String> sampleSerialNumberList = list.stream().map(LabinfoItemData::getSampleSerialNumber).collect(Collectors.toList());
                //批量查询
                List<LabinfoSampleData> sampleList = iLabinfoSampleDataService.getSampleListByList(sampleSerialNumberList);
                if(CollectionUtil.isNotEmpty(sampleList)){ //sampleList转成map
                    Map<String, List<LabinfoSampleData>> map = sampleList.stream()
                            .collect(Collectors.groupingBy(LabinfoSampleData::getSampleSerialNumber));
                    //遍历list
                    list.stream().forEach(labinfoItemData1 -> {
                        String sampleSerialNumber = labinfoItemData1.getSampleSerialNumber();
                        if(StringUtils.isNotEmpty(sampleSerialNumber) && map.get(sampleSerialNumber) != null){
                            List<LabinfoSampleData> labinfoSampleDataList = map.get(sampleSerialNumber);
                            if(CollectionUtil.isNotEmpty(labinfoSampleDataList)){
                                labinfoItemData1.setSampleList(labinfoSampleDataList);
                            }
                        }
                    });
                }
            }
        }
        return getDataTable(list);
    }



    /**
     * 分享内容
     */
//    @PreAuthorize("@ss.hasPermi('system:custom:audit')")
    @PutMapping("/shareItems")
    @Log(title = "分享检测服务", businessType = BusinessType.SHARE)
    public AjaxResult shareItems(@RequestBody LabinfoItemData labinfoItemData)
    {
        return toAjax(labinfoItemDataService.shareItems(labinfoItemData));
    }


    //根据送检单位和受检人姓名获取受检人所有送检时间
    @PostMapping(value = "/getReceiveItemDateList")
    public AjaxResult getReceiveSampleDateList(@RequestBody Map map) {
        List<Map> labinfoSampleDataList = labinfoItemDataService.getReceiveItemDateList(map);
        return success(labinfoSampleDataList);
    }

    //根据送检单位和受检人姓名,送检日期，获取受检人的信息
    @PostMapping(value = "/getItemByReceiveDate")
    public AjaxResult getItemByReceiveDate(@RequestBody Map map) {
        List<LabinfoItemData> itemList = labinfoItemDataService.getItemByReceiveDate(map);
        return success(itemList);
    }
}
